﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UCNKompetenceBors.Database;
using UCNKompetenceBors.Model;

namespace UCNKompetenceBors.Admin
{
    public partial class adminContactPersonEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.Form.DefaultButton = btnAdminEditContactPerson.UniqueID;

                BindSubMenu();
                BindData(Convert.ToInt32(Request.QueryString["cpid"]));

                lblConfirmUpdatedContactPerson.Visible = false;

                #region Globalization
                string culture = String.Empty;

                if (HttpContext.Current.Session["MyCulture"] != null)
                    culture = HttpContext.Current.Session["MyCulture"].ToString();

                if (!String.IsNullOrEmpty(culture))
                    GeneralTools.SetCulture(culture);

                LocalizeControls();
                #endregion
            }
        }

        /// <summary>
        /// Binds the sub menu links.
        /// </summary>
        private void BindSubMenu()
        {
            hyLinkAdminDashboard.NavigateUrl = "~/Admin/admin.aspx";
            hyLinkUserHandling.NavigateUrl = "~/Admin/adminUsers.aspx";
            hyLinkAdminExchange.NavigateUrl = "~/Admin/adminExchange.aspx";
            hyLinkNewsHandling.NavigateUrl = "~/Admin/adminNews.aspx";
            hyLinkEditInformation.NavigateUrl = "~/Admin/adminInformation.aspx";
            hyLinkResetUsers.NavigateUrl = "~/Admin/adminUsersReset.aspx";
            hyLinkCreateContactPerson.NavigateUrl = "~/Admin/adminContactPersonCreate.aspx";
            hyLinkContactPerson.NavigateUrl = "~/Admin/adminContactPerson.aspx";
            hylinkDepartment.NavigateUrl = "~/Admin/adminDepartment.aspx";
        }

        /// <summary>
        /// Binds the controls with a contact person based on the contactPersonId parameter.
        /// </summary>
        /// <param name="contactPersonId">Specifies the ID of the contact person to be used.</param>
        private void BindData(int contactPersonId)
        {
            ContactPerson contact = dbAdmin.GetContactPersonById(contactPersonId);

            txtEditContactPersonFname.Text = contact.FirstName;
            txtEditContactPersonLname.Text = contact.LastName;
            txtEditContactPersonPhone.Text = contact.Phone;
            txtEditContactPersonEmail.Text = contact.Email;
            txtEditContactPersonTitle.Text = contact.Title;
            txtEditContactPersonDepartment.Text = contact.Department;
            imgEditContactPersonImage.ImageUrl = contact.ImageURL;
        }

        /// <summary>
        /// Edits a contact person, based on the contactPersonId parameter.
        /// </summary>
        /// <param name="contactPersonId">Specifies the ID of the contact person to be used.</param>
        /// <param name="fName">Specifies the first name to be used.</param>
        /// <param name="lName">Specifies the last name to be used.</param>
        /// <param name="hasImage">Specifies whether or not news article has an image.</param>
        /// <param name="imageFileName">Specifies the file name of the image to be used.</param>        
        /// <param name="phone">Specifies the phone to be used.</param>
        /// <param name="email">Specifies the email to be used.</param>
        /// <param name="title">Specifies the title to be used.</param>
        /// <param name="department">Specifies the department to be used</param>
        public void EditContactPerson(int contactPersonId, string fName, string lName, bool hasImage, string imageFileName, string phone, string email, string title, string department)
        {
            string path = "";

            //Checks whether or not an image has been selected in the fileupload control
            if (hasImage)
            {
                //Checks whether or not current image is the default image
                if (!imgEditContactPersonImage.ImageUrl.Equals("~/Images/ContactPersons/defaultCp.jpg"))
                {
                    //If the current image is not the default image, the old image is deleted
                    DeleteImage(Convert.ToInt32(Request.QueryString["nid"]), imgEditContactPersonImage.ImageUrl);
                    path = Path.GetDirectoryName(imgEditContactPersonImage.ImageUrl);
                }
                else
                {
                    path = Path.GetDirectoryName("~/Images/ContactPersons/" + txtEditContactPersonFname.Text.Trim() + "_" + txtEditContactPersonLname.Text + "/");
                }

                UploadPicture();
            }

            dbAdmin.EditContactPerson(contactPersonId, fName, lName, hasImage, path, imageFileName, phone, email, title, department);
        }

        /// <summary>
        /// Upload an image.
        /// </summary>
        private void UploadPicture()
        {
            string path = Server.MapPath("~/Images/ContactPersons/" + txtEditContactPersonFname.Text.Replace(" ", "") + "_" + txtEditContactPersonLname.Text.Trim() + "/");
            if (!Directory.Exists(path))
            {
                DirectoryInfo dir = new DirectoryInfo(path);

                dir.Create();
            }

            if (fuEditContactPersonImage.HasFile)
            {
                System.Drawing.Image image = System.Drawing.Image.FromStream(fuEditContactPersonImage.FileContent);
                string imagePath = path + fuEditContactPersonImage.FileName;

                GeneralTools.CreateThumbnail(100, image, imagePath);
            }
        }

        /// <summary>
        /// Checks whether or not a contact person has an image, based on the contactPersonId parameter.
        /// </summary>
        /// <param name="contactPersonId">Specifies the ID of the contact person to be used.</param>
        /// <returns>Returns a boolean, specifying whether or not a contact person has an image.</returns>
        private bool HasImage(int contactPersonId)
        {
            return dbAdmin.ContactPersonHasImage(contactPersonId);
        }

        /// <summary>
        /// Deletes an image, based on the contactPersonId and imagePath parameters.
        /// </summary>
        /// <param name="contactPersonId">Specifies the ID of the contact person to be used.</param>
        /// <param name="imagePath">Specifies the path of the image to be deleted</param>
        private void DeleteImage(int contactPersonId, string imagePath)
        {
            if (HasImage(contactPersonId))
            {
                string filePath = HttpContext.Current.Server.MapPath(imagePath);

                //Removes the filename from the path
                string path = Path.GetDirectoryName(filePath);

                File.Delete(filePath);
            }
        }

        protected void btnAdminEditContactPerson_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                lblConfirmUpdatedContactPerson.Visible = true;
                int contactPersonId = Convert.ToInt32(Request.QueryString["cpid"]);
                string fName = txtEditContactPersonFname.Text;
                string lName = txtEditContactPersonLname.Text;
                bool hasImage = fuEditContactPersonImage.HasFile;
                string imageFileName = fuEditContactPersonImage.FileName;
                string phone = txtEditContactPersonPhone.Text;
                string email = txtEditContactPersonEmail.Text;
                string title = txtEditContactPersonTitle.Text;
                string department = txtEditContactPersonDepartment.Text;                

                EditContactPerson(contactPersonId, fName, lName, hasImage, imageFileName, phone, email, title, department);

                BindData(contactPersonId);
            }
        }

        /// <summary>
        /// Localizes the controls of the site, based on the current UI Culture.
        /// </summary>
        private void LocalizeControls()
        {
            hyLinkAdminDashboard.Text = GetLocalResourceObject("hyLinkAdminDashboardText").ToString();
            hyLinkUserHandling.Text = GetLocalResourceObject("hyLinkUserHandlingText").ToString();
            hyLinkAdminExchange.Text = GetLocalResourceObject("hyLinkAdminExchangeText").ToString();
            hyLinkNewsHandling.Text = GetLocalResourceObject("hyLinkNewsHandlingText").ToString();
            hyLinkEditInformation.Text = GetLocalResourceObject("hyLinkEditInformationText").ToString();
            hyLinkResetUsers.Text = GetLocalResourceObject("hyLinkResetUsersText").ToString();
            hylinkDepartment.Text = GetLocalResourceObject("hylinkDepartmentText").ToString();

            hyLinkContactPerson.Text = GetLocalResourceObject("hyLinkContactPersonText").ToString();
            hyLinkCreateContactPerson.Text = GetLocalResourceObject("hyLinkCreateContactPersonText").ToString();

            lblAdminContentHeader.Text = GetLocalResourceObject("lblAdminContentHeaderText").ToString();
            lblEditContactPersonFname.Text = GetLocalResourceObject("lblEditContactPersonFnameText").ToString();
            lblEditContactPersonLname.Text = GetLocalResourceObject("lblEditContactPersonLnameText").ToString();
            lblEditContactPersonPhone.Text = GetLocalResourceObject("lblEditContactPersonPhoneText").ToString();
            lblEditContactPersonEmail.Text = GetLocalResourceObject("lblEditContactPersonEmailText").ToString();
            lblEditContactPersonTitle.Text = GetLocalResourceObject("lblEditContactPersonTitleText").ToString();
            lblEditContactPersonDepartment.Text = GetLocalResourceObject("lblEditContactPersonDepartmentText").ToString();
            lblEditContactPersonImage.Text = GetLocalResourceObject("lblEditContactPersonImageText").ToString();
            lblConfirmUpdatedContactPerson.Text = GetLocalResourceObject("lblConfirmUpdatedContactPersonText").ToString();

            btnAdminEditContactPerson.Text = GetLocalResourceObject("btnAdminEditContactPersonText").ToString();
            btnCancelEditContactPerson.Text = GetLocalResourceObject("btnCancelEditContactPersonText").ToString();

            string imageRegexValidaton = GetLocalResourceObject("regexvalEditContactPersonImageText").ToString();
            regexvalEditContactPersonImage.ToolTip = imageRegexValidaton;
            regexvalEditContactPersonImage.ErrorMessage = imageRegexValidaton;

            string fNameValidation = GetLocalResourceObject("rfvalFnameText").ToString();
            rfvalFname.ToolTip = fNameValidation;
            rfvalFname.ErrorMessage = fNameValidation;

            string lNameValidation = GetLocalResourceObject("rfvalLnameText").ToString();
            rfvalLname.ToolTip = lNameValidation;
            rfvalLname.ErrorMessage = lNameValidation;

            string emailValidation = GetLocalResourceObject("rfvalEditContactPersonEmailText").ToString();
            rfvalEditContactPersonEmail.ToolTip = emailValidation;
            rfvalEditContactPersonEmail.ErrorMessage = emailValidation;

            string emailRegexValidaton = GetLocalResourceObject("regexvalEmailText").ToString();
            regexvalEmail.ToolTip = emailRegexValidaton;
            regexvalEmail.ErrorMessage = emailRegexValidaton;

            string phoneRegexValidaton = GetLocalResourceObject("regexvalPhoneText").ToString();
            regexvalPhone.ToolTip = phoneRegexValidaton;
            regexvalPhone.ErrorMessage = phoneRegexValidaton;

            string titleValidation = GetLocalResourceObject("rfvalEditContactPersonTitleText").ToString();
            rfvalEditContactPersonTitle.ToolTip = titleValidation;
            rfvalEditContactPersonTitle.ErrorMessage = titleValidation;

            string departmentValidation = GetLocalResourceObject("rfvalEditContactPersonDepartmentText").ToString();
            rfvalEditContactPersonDepartment.ToolTip = departmentValidation;
            rfvalEditContactPersonDepartment.ErrorMessage = departmentValidation;

            valSumAdminEditContactPerson.HeaderText = GetLocalResourceObject("valSumAdminEditContactPersonText").ToString();
        }

        protected void btnCancelEditContactPerson_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/adminContactPerson.aspx");
        }
    }
}